package main

import (
	"fmt"
	"go_code/day15/database"
)

type Employee struct {
	Id             uint
	Name           string         `gorm:"size:20"`
	EmployeeDetail EmployeeDetail `gorm:"foreignKey:EmployeeId;references:Id;cascade:delete"` // 添加了级联删除
}

func (e Employee) TableName() string {
	return "employee"
}

type EmployeeDetail struct {
	Id         uint
	Addr       string `gorm:"size:100"`
	Phone      string `gorm:"size:11"`
	EmployeeId uint   `gorm:"index"` //确保外键字段有索引
}

func (e EmployeeDetail) TableName() string {
	return "employee_detail"
}

func main() {
	db := database.DB()
	db.AutoMigrate(&Employee{}, &EmployeeDetail{})

	// emp := Employee{
	// 	Name: "小刚",
	// 	EmployeeDetail: EmployeeDetail{
	// 		Addr:  "北京市朝阳区",
	// 		Phone: "17712345678",
	// 	},
	// }
	// err := db.Create(&emp).Error
	// if err != nil {
	// 	panic(err)
	// }
	// fmt.Println("数据添加成功")

	var emp []Employee
	// db.Preload("EmployeeDetail").Where("id = ?", 1).First(&emp)
	db.Preload("EmployeeDetail").Find(&emp)
	// fmt.Println(emp)
	for _, value := range emp {
		fmt.Println(value.Id, value.Name, value.EmployeeDetail.Addr, value.EmployeeDetail.Phone)
	}

	// db.Where("id = ?", 1).First(&emp)
	// count := db.Unscoped().Delete(&emp).RowsAffected
	// fmt.Println("删除成功，数量：", count)
}
